<template>
    <div class="app-container">
        <!-- 合并后删除 -->
        <!-- <el-form :model="queryParams" ref="queryForm" :inline="true">

      <el-form-item label="自然年" prop="naturalYearName">
        <el-select
          v-model="queryParams.naturalYearName"
          placeholder="请选择自然年份"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in naturalYearList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="周期名称" prop="cycleName">
        <el-input
          v-model="queryParams.cycleName"
          placeholder="请输入周期名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form> -->

        <el-row :gutter="10" class="fromYear mb20">
            <el-col :span="1.5">来自自然年</el-col>
            <el-col :span="0.5">-</el-col>
            <el-col :span="1.5">{{ queryParams.naturalYearName }}</el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['training:annualPlan:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['training:annualPlan:remove']">删除</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="annualPlanList" @selection-change="handleSelectionChange" height="300" style="100%">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="自然年" align="center" prop="naturalYearName" width="100" />
            <el-table-column label="周期名称" align="center" prop="cycleName" />
            <el-table-column label="开始时间" align="center" prop="startTime" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="ctime" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.ctime, "{y}-{m}-{d}") }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['training:annualPlan:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['training:annualPlan:remove']">删除</el-button>
                    <!-- 合并后隐藏 -->
                    <!-- <el-button size="mini" type="text">
            <router-link
              :to="'/plan/trainingWeek?annualPlanId=' + scope.row.id"
              class="link-type"
            >
              <span>训练周</span>
            </router-link>
          </el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- 合并后删除 -->
        <!-- <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

        <!-- 添加或修改annualPlan对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="自然年" prop="naturalYeaId" style="width: 300px">
                    <el-select v-model="form.naturalYearId" placeholder="请选择自然年份" disabled size="small">
                        <el-option v-for="dict in naturalYearList" :key="dict.id" :label="dict.name" :value="dict.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="周期名称" prop="cycleName" style="width: 300px" required>
                    <el-input v-model="form.cycleName" placeholder="请输入周名称" style="width: 200px" />
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime" required>
                    <el-date-picker clearable size="small" style="width: 200px" v-model="form.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择开始时间" :picker-options="startTimeLimit">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime" required>
                    <el-date-picker clearable size="small" style="width: 200px" v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="选择结束时间" :picker-options="endTimeLimit">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listAnnualPlan, listNaturalYear, getAnnualPlan, delAnnualPlan, addAnnualPlan, updateAnnualPlan, exportAnnualPlan } from "@/api/training/annualPlan";
import eventBus from "@/components/eventBus.js";

export default {
    name: "stagePlan",
    props: ["naturalYearDetails"],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // annualPlan表格数据
            annualPlanList: [],
            //自然年份集合
            naturalYearList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                // pageNum: 1,
                // pageSize: 10,
                naturalYearName: undefined,
                naturalYearId: undefined,
                cycleName: undefined,
                startTime: undefined,
                endTime: undefined,
                ctime: undefined,
                ltime: undefined,
            },
            // 表单参数
            form: {},
            startTimeLimit: this.pickerStartDate(),
            endTimeLimit: this.pickerEndDate(),
            // 表单校验
            rules: {
                cycleName: [
                    { required: true, message: "周期名称不能为空", trigger: "blur" },
                ],
                startTime: [
                    { required: true, message: "开始日期不能为空", trigger: "blur" },
                ],
                endTime: [
                    { required: true, message: "结束日期不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {
        this.getList();
        this.getNaturalYearList();
        // 监听最新自然年
        this.$set(this.naturalYearDetails);
    },
    mounted() {
        // 接收组件year传递过来的自然年详情
        eventBus.$on("naturalYearDetails", (message) => {
            // this.queryParams.naturalYearName = JSON.parse(message).name;
            // this.queryParams.naturalYearId = JSON.parse(message).id
            // this.getList();
        });

    },
    watch: {
        // 监听最新自然年
        naturalYearDetails: {
            handler(newVal, oldVal) {
                this.queryParams.naturalYearName = this.naturalYearDetails.name;
                this.queryParams.naturalYearId = this.naturalYearDetails.id
                this.getList();
            },
            deep: true,
        },
    },
    methods: {
        /**开始日期选择：如果先选结束日期，则日期不能大于结束日期且不能早于自然年开始日期；如果没有先选结束日期，日期则不能小于自然年开始日期且不能大于自然年结束日期； **/
        pickerStartDate() {
            var _this = this;
            return {
                disabledDate(time) {
                    var endDateStr = new Date(_this.form.endTime).getTime();// 开始日期时间戳
                    var time1 = new Date(_this.naturalYearDetails.startTime).getTime();// 开始日期时间戳
                    var time2 = new Date(_this.naturalYearDetails.endTime).getTime();// 结束日期时间戳
                    let a = time.getTime() > endDateStr- 24 * 60 * 60 * 1000;// 不能大于结束日期
                    let b = time.getTime() < time1- 24 * 60 * 60 * 1000 //  不能早于自然年开始日期
                    let c = time.getTime() > time2  // 不能大于自然年的结束日期
                    return endDateStr ? (a || b) : (b || c);
                }
            }
        },
        /**开始日期选择：如果先选开始日期，则日期不能小于开始日期且不能大于自然年结束日期；否则，则日期不能小于自然年开始日期且不能大于自然年结束日期 **/
        pickerEndDate() {
            var _this = this;
            return {
                disabledDate(time) {
                    var startDateStr = new Date(_this.form.startTime).getTime();// 开始日期时间戳
                    var time1 = new Date(_this.naturalYearDetails.startTime).getTime();// 开始日期时间戳
                    var time2 = new Date(_this.naturalYearDetails.endTime).getTime();// 结束日期时间戳
                    let a = time.getTime() < startDateStr- 24 * 60 * 60 * 1000;// 不能小于结束日期
                    let b = time.getTime() < time1- 24 * 60 * 60 * 1000 //  不能早于自然年开始日期
                    let c = time.getTime() > time2  // 不能大于自然年的结束日期
                    return startDateStr ? (a || c) : (b || c);
                }
            }
        },
        /** 查询annualPlan列表 */
        getList() {
            this.loading = true;
            listAnnualPlan(this.queryParams).then((response) => {
                this.annualPlanList = response.rows;
                this.total = response.total;
                console.log(this.annualPlanList)
                this.loading = false;
            });
        },

        //自然年份集合
        getNaturalYearList() {
            this.loading = true;
            listNaturalYear(this.queryParams).then((response) => {
                this.naturalYearList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                naturalYearName: undefined,
                cycleName: undefined,
                startTime: undefined,
                endTime: undefined,
                ctime: undefined,
                ltime: undefined,
                naturalYearId: this.queryParams.naturalYearId
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加年度计划";
            this.pickerStartDate();
            this.pickerEndDate()
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getAnnualPlan(id).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改年度计划";
                this.pickerStartDate();
                this.pickerEndDate()
            });

        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateAnnualPlan(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        addAnnualPlan(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm(
                '是否确认删除annualPlan编号为"' + ids + '"的数据项?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(function () {
                    return delAnnualPlan(ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm("是否确认导出所有annualPlan数据项?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return exportAnnualPlan(queryParams);
                })
                .then((response) => {
                    this.download(response.msg);
                })
                .catch(function () { });
        },
    },
};
</script>

<style lang="scss" scoped>
.app-container {
    padding: 0;
}
.fromYear {
    color: #67c23a;
    height: 38px;
    line-height: 38px;
    font-size: 14px;
}
.el-table::before {
    height: 0px;
}
</style>